Traverse a Square - Part N - Functions

tricky because of scoping - need to think carefully about this....

In the previous notebook on this topic, we had described how to use a loop that could run the same block of code multiple times so that we could avoid repeating ourselves in the construction of program to drive a mobile robot along a square shaped trajectory.

One possible form of the program was as follows - note the use of varaiables to specify several parameter values:

import time

side_speed=2
side_length_time=1
turn_speed=1.8
turn_time=0.45

number_of_sides=4

for side in range(number_of_sides):

    #side
    robot.move_forward(side_speed)
    time.sleep(side_length_time)

    #turn
    robot.rotate_left(turn_speed)
    time.sleep(turn_time)

Looking at the program, we have grouped the lines of code inside the loop into two separate meaningful groups:

  • one group of lines to move the robot in a straight line along one side of the square;
  • one group of lines to turn the robo through ninety degrees.

We can further abstract the program into one in which we define some custom functions that can be called by name and that will execute a code block captured within the function definition.

Here's an example:


In [ ]:
import time

def myFunction():
    print("Hello...")
    
    #Pause awhile...
    time.sleep(2)
    
    print("...world!")
    
#call the function - note the brackets!
myFunction()

The function definition takes the following, minimal form:

def NAME_OF_FUNCTION():
    #Code block - there must be at least one line of code
    #That said, we can use a null (do nothing) statement
    pass

Set up the notebook to use the simulator and see if you can think of a way to use functions to call the lines of code that control the robot.

The function definitions should appear before the loop.


In [ ]:
%run 'Set-up.ipynb'
%run 'Loading scenes.ipynb'
%run 'vrep_models/PioneerP3DX.ipynb'

In [ ]:
%%vrepsim '../scenes/OU_Pioneer.ttt' PioneerP3DX

#Your code  - using functions - here

How did you get on? Could you work out how to use the functions?

Here's how I used them:


In [ ]:
%%vrepsim '../scenes/OU_Pioneer.ttt' PioneerP3DX
import time

side_speed=2
side_length_time=1
turn_speed=1.8
turn_time=0.45

number_of_sides=4

def traverse_side():
     
    pass
def turn():
    pass
    
for side in range(number_of_sides):
        
    #side
    robot.move_forward(side_speed)
    time.sleep(side_length_time) 
    
    #turn
    robot.rotate_left(turn_speed)
    time.sleep(turn_time)

computational thinking